import {
	addArticle,
	findAllArticle,
	updateArticleByOption
} from '../services/articleService'

import {
	addTag,
} from '../services/tagService'

/**
 * 写文章
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
let INSERT_ARTICLE = async (ctx, next) => {
	const body = ctx.request.body;
	//创建文章并新增标签
	if(body.tagName) {
		let tagItem = await addTag({
			name: body.tagName,
			description: ''
		}).catch((err) => { console.error(err) });
		body.tag = [...body.tag, tagItem._id] ;
	}
	let articleItem = await addArticle(body).catch((err) => { console.error(err) });
	ctx.success(articleItem, '数据写入成功')
};

/**
 * 根据条件查询所有文章,排序
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
let FINDALL_ARTICLE = async (ctx, next) => {
	const { sort = -1, page = 1, id = '', type = '', keyword = '' } = ctx.request.query;
	let options = {
		sort : { create_at: sort },
		page: page
	};
	let query = {
		tag: id,
		type,
		keyword,
	};
	let articleList = await findAllArticle(query, options).catch((err) => { console.error(err) });
	articleList.docs.map(item => item.content = '');
	ctx.success(articleList, '获取数据成功');
};

/**
 * 查询单个文章，并更新文章浏览量
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
let GET_ARTICLE_DETAIL = async (ctx, next) => {
	const { id } = ctx.params;
	let articleItem = await updateArticleByOption({name: '_id', value: id}, {type: 'views'}).catch((err) => { console.error(err) });
	ctx.success(articleItem, '获取文章内容成功');
};

/**
 * 点赞文章
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
let POST_LIKE_ARTICLE = async (ctx, next) => {
	const { id } = ctx.params;
	let articleItem = await updateArticleByOption({name: '_id', value: id}, {type: 'likes'}).catch((err) => { console.error(err) });
	ctx.success(articleItem, '文章点赞成功');
};

module.exports = {
	'POST /api/article/add': INSERT_ARTICLE,
	'GET /api/article': FINDALL_ARTICLE,
	'GET /api/article/:id': GET_ARTICLE_DETAIL,
	'GET /api/article/like/:id': POST_LIKE_ARTICLE
};

